<template>
    <div>
        <el-form size="mini" :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item size="mini" label="手机号">
                <el-input v-model="formInline.phone" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item size="mini" label="用户名">
                <el-input v-model="formInline.username" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item size="mini" label="宠物名称">
                <el-input v-model="formInline.petname" placeholder="宠物名称"></el-input>
            </el-form-item>
            <el-form-item label="宠物类型">
                <el-select clearable v-model="formInline.type" placeholder="寄存类型">
                    <el-option label="猫" value="猫"></el-option>
                    <el-option label="狗" value="狗"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="寄存时间">
                <el-date-picker v-model="value2" type="datetimerange" :picker-options="pickerOptions" range-separator="至"
                    start-placeholder="开始日期" end-placeholder="结束日期" align="right">
                </el-date-picker>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="searchSubmit">查询</el-button>
            </el-form-item>

            <el-form-item v-if="showFormItem">
                <el-button type="primary" circle icon="el-icon-edit" @click="addorEditFoster('add')"></el-button>
            </el-form-item>
            <!-- 添加寄养用户抽屉 -->
            <el-dialog center custom-class="foster-add-dialog" :title="title" :visible.sync="dialogFormVisible">
                <el-form :model="fosterRuleForm" :rules="fostersRules" ref="fosterRuleForm" label-position="left"
                    label-width="80px" size="mini">
                    <el-form-item label="用户名" prop="username">
                        <el-input v-model="fosterRuleForm.username" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item size="mini" label="手机号" prop="phone">
                        <el-input v-model="fosterRuleForm.phone" placeholder="手机号"></el-input>
                    </el-form-item>
                    <el-form-item size="mini" label="宠物名称" prop="petname">
                        <el-input v-model="fosterRuleForm.petname" placeholder="宠物名称"></el-input>
                    </el-form-item>
                    <el-form-item size="mini" label="寄养状态" prop="status">
                        <el-input v-model="fosterRuleForm.status" placeholder="寄养状态"></el-input>
                    </el-form-item>
                    <el-form-item label="宠物类型" prop="type">
                        <el-select clearable v-model="fosterRuleForm.type" placeholder="寄存类型">
                            <el-option label="猫" value="猫"></el-option>
                            <el-option label="狗" value="狗"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="寄存时间">
                        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="value3" type="datetimerange"
                            :picker-options="pickerOptions" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期" align="right">
                        </el-date-picker>
                    </el-form-item>
                </el-form>

                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="Submit">确 定</el-button>
                </div>
            </el-dialog>

        </el-form>
        <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange">
 
            <el-table-column label="序号" width="50" type=index>
                <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column label="用户名" prop="username" width="120">
            </el-table-column>
            <el-table-column label="宠物类型" prop="type" width="100">
            </el-table-column>
            <el-table-column label="宠物名字" prop="petname" width="120">
                <template slot-scope="scope">{{ scope.row.petname }}</template>
            </el-table-column>
            <el-table-column label="手机号" prop="phone" width="120">
            </el-table-column>
            <el-table-column label="开始时间" prop="starttime" width="120">
            </el-table-column>
            <el-table-column label="结束时间" prop="endtime" width="120">
            </el-table-column>
            <el-table-column label="寄养状态" width="120">
                <template slot-scope="scope">{{ fosterStatus[scope.row.status] }}</template>
            </el-table-column>
            <el-table-column fixed="right" label="操作" width="100">
                <template slot-scope="scope">
                    <el-button @click="delone(scope.row.id)" type="text" size="small">删除</el-button>
                    <el-button @click="addorEditFoster('edit', scope.row)" type="text" size="small">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>
        <a-pagination :pageSize="limit" v-model="pageNum" @change="handleCurrentChange" :default-current="1"
            :total="totalcount" />


    </div>
</template>

<script>
import { Foster } from "./../../api"
export default {
    name: 'FosterTable',
    props: {
        tableData: Array,
        totalcount: {
            default: 0,
            type: Number
        },
        limit: {
            default: 5,
            type: Number
        },
        showFormItem: {
            default: false,
            type: Boolean
        },
        // fudialogFormVisible: {
        //     default: false,
        //     type: Boolean
        // },
    },
    data() {
        var validateUsername = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('用户名不能为空'));
            }
            callback()
        };
        var validatePhone = (rule, value, callback) => {
            console.log(rule, value, callback);
            if (!value) {
                callback(new Error('请输入用户手机号'));
            } else {
                const regex = /^1[3456789]\d{9}$/; // 正则表达式，验证手机号码格式
                if (regex.test(this.fosterRuleForm.phone)) {
                    // 使用正则表达式进行验证
                    callback()
                } else {
                    callback(new Error('手机号格式不正确'))
                }
            }
        }

        return {
            title: '添加用户',
            pageNum: 1,
            activeName: 'first',
            fosterStatus: [
                "寄养中",
                "寄养结束"
            ],
            tableHead: [
                "会员名称",
                "宠物名称",
                "宠物类型",
                "寄养开始",
                "预计结束",
                "寄养状态",
                "手机号",
                "监控ld",
                "备注"
            ],
            //寄养筛选
            formInline: {
                username: '',
                phone: '',
                petname: '',
                type: '',
                starttime: '',
                endtime: ''
            },
            //日期
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
            //选择的日期头尾数组
            value2: [],
            value3: [],
            //编辑寄养用户ui
            dialogFormVisible: false,
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            formLabelWidth: '120px',
            //新增或者编辑一个寄养人的规则表单验证
            fosterRuleForm: {
                username: '',
                phone: '',
                petname: '',
                type: '',
                starttime: '',
                endtime: '',
                status:0
            },
            fostersRules: {
                username: [
                    { validator: validateUsername, trigger: 'blur' }
                ],
                phone: [
                    { validator: validatePhone, trigger: 'blur' }
                ],
                petname: [
                    { required: true, message: '宠物名不能为空', trigger: 'blur' }
                ],
                type: [
                    { required: true, message: '宠物类型不能为空', trigger: 'blur' }
                ],
                starttime: [
                    { required: true, message: '开始寄存时间不能为空', trigger: 'blur' }
                ],
                endtime: [
                    { required: true, message: '结束寄存时间不能为空', trigger: 'blur' }
                ],
            },

            multipleSelection: []
        }
    },
    watch: {
        value2: {//查询
            deep: true,
            handler(newValue, oldValue) {//这里的第一个参数是改变后的值，第二个参数是原来的值
                // this.fosterData()
                if (newValue != null) {
                    this.$data.formInline.starttime = newValue[0]
                    this.$data.formInline.endtime = newValue[1]
                }
            },
            immediate: true
        },
    },
    mounted() {

        // this.$emit('changeChangeCount', "jjj")
        this.$emit('changePageNum', this.$data.pageNum)
    },
    methods: {
        // 定义一个方法，将任意时间格式转换为 'yyyy-MM-dd HH:mm:ss' 格式
        formatDateTime(inputTime) {
            const date = new Date(inputTime);

            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');

            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        },
        addorEditFoster(title, row) {
            this.$data.dialogFormVisible = true
            //有row就是没有数据，那么就是编辑
            if (row != undefined) {
                // console.log(row.starttime, "row的时间yyyy-MM-dd HH:mm:ss");
                // console.log(this.$moment(row.starttime).format('yyyy-MM-dd HH:mm:ss'), "row99的时间");这个方法没有需要的格式
                //(其实就是表格在打开时，本来是空的，但是先把row的数据赋值给value3，value3和表格时间双向绑定。然后把其他的row赋值给fosterRuleFom，而这个对象和表格本身双向绑定，需要把时间单独绑定是因为时间是一个数组，对象不能把两个属性直接赋值给一个数组)
                this.$data.title = "编辑用户"
                //因为value3是用来盛装编辑和添加表格日期数组的，而且是v-model，这里也是相当于赋值，但是当编辑的时候，里面的数据是不支持放到表格，所以现用插件转换成可以使用的格式
                this.value3 = [this.formatDateTime(row.starttime), this.formatDateTime(row.endtime)]    // element必须的日期数据格式
                //然后把当前表格都赋值
                this.$data.fosterRuleForm = { ...row }
            } else {
                //没有row就是添加用户
                this.$data.title = "添加用户"
                this.value3 = []
                // this.$data.fosterRuleForm = {
                //     username: '',
                //     phone: '',
                //     petname:'',
                //     type: '',
                //     starttime: this.value3[0],
                //     endtime: this.value3[1]
                // }
            }
        },
        searchSubmit() {
            this.$emit("searchFoster", this.$data.formInline)
        },
        //在添加或者编辑用户之后，点击提交，需要把当前页面数据通过事件交给父组件处理，并且需要关闭当前的表格
        Submit() {
            this.$refs.fosterRuleForm.validate((valid) => {
                if (valid) {
                    this.$data.dialogFormVisible = false
                    //因为对象和表格双向绑定，所以在这里对象除了时间都是赋值了
                    let foster = this.$data.fosterRuleForm
                    //无论是添加还是编辑，在提交的时候value3都是因为表格有值而有数据的，并且在这个组件上方是有格式设置在的
                    foster.starttime = this.value3[0]//不要从上面的对象里面赋值，要直接从value3里面赋值，否则时间格式就不正确
                    foster.endtime = this.value3[1]
                    let atitle = this.title
                    this.$emit("submitFosterInfo", { foster, atitle })
                    for (let key in foster) {
                        foster[key] = ''; // 给属性赋空字符串的值
                    }
                } else {
                    // 表单验证不通过，提示用户
                    this.$message.error('请填写所有必填字段');
                    return false;
                }
            });

        },
        delone(id) {
            console.log(id + "删除的id")
            this.$confirm({
                title: '删除寄养信息后无法恢复,确认删除吗？',
                content: h => <div style="color:red;">删除吗？</div>,
                onOk: async () => {
                    console.log('OK');
                    let res = await Foster['del'](id)
                    this.$emit('changePageNum', this.$data.pageNum)
                    console.log(res + "删除寄养信息后的值")
                },
                onCancel() {
                    console.log("取消")
                },
                class: 'test',
            });
        },
        //数据太少没分页，不确定是否好使
        handleCurrentChange(val) {
            // this.$props.pageNum = val
            console.log(this.$data.pageNum + "当前页数");
            console.log(this.$props.totalcount + "总页数");
            this.$emit('changePageNum', this.$data.pageNum)
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
    }
}
</script>

<style scoped></style>